package com.his.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * @author bajin
 */
public final class RsaUtils {
    /**
     * 解密私钥的key
     */
    // private static final String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMdg94JaoT4ZCNBo\n" +
    //         "ZgD47A6lVJ9SSr6s0dsRCr+4TaRgw5+RbH8atvhQ22nVUXuPS/VamU8/RxE5wfaI\n" +
    //         "o115MjH3WntrqiPclkADfrOfhTPEPC+zOAHgIzSTMS8tl5KfteLogv5c6zrGAt0c\n" +
    //         "D1HNd69zW8Lxy4T2njjnj/i4XEFJAgMBAAECgYAUljeYVyFVFyKo2k7GBO3i6UFe\n" +
    //         "nhGntJKKqyzP9QjXU0J/xHVOfoSsCTVOrT8Xogk20V8JJsCAz9TuTteHfE8pWOoA\n" +
    //         "Bz2gqyEltJLpCIydy1O8bkKlV2H+3vYl1jhgFwBo3wCaDoq1Ffv545CY+1CUT1vs\n" +
    //         "9HBmq+kp0vRcQ5nb8QJBAO02t+/GPdon8QZtGD28iRzKfBp1/TJiPrmuGb7qHqIz\n" +
    //         "IzzotcTJfCUhE0n6RrXuB7hzMnAp3kFf3SCfXG67Tl0CQQDXKy47oQRvPSKMT2Y2\n" +
    //         "Z8Ty0hC8ZDadNYHJbu14II9dizpDjO1XX+obhs95ikKEZKIYfhjfP7QWlo1BUKd8\n" +
    //         "qFfdAkEA5jpgZWgbqftwE9OYXnr4/KeNscToXJk71c0jEcd6ueQ2BCy8FmWThxnF\n" +
    //         "9dvh+zst5RhxUKliHEMlhD8HYDWMxQJBAMZYgsTq+EiGxZsr8iAC5lWkeVMA2itv\n" +
    //         "UJXcUMGk2iO0HWB5v6wEuazoR8dVQV4D2jzTuJ/LfHo6DDqCW/KYyG0CQG6f7jpZ\n" +
    //         "PE3iou/NKDIIZhWA0dBuRddjREBajTBkiBTSTDH/TBLYXmhq8rS8NrVyPtd4icIB\n" +
    //         "qfszJV5Nesgt0Zo=";
    // /**
    //  * 加密公钥的key
    //  */
    // private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDHYPeCWqE+GQjQaGYA+OwOpVSf\n" +
    //         "Ukq+rNHbEQq/uE2kYMOfkWx/Grb4UNtp1VF7j0v1WplPP0cROcH2iKNdeTIx91p7\n" +
    //         "a6oj3JZAA36zn4UzxDwvszgB4CM0kzEvLZeSn7Xi6IL+XOs6xgLdHA9RzXevc1vC\n" +
    //         "8cuE9p4454/4uFxBSQIDAQAB";
    // /**
    //  * RSA最大加密明文大小
    //  */
    // private static final int MAX_ENCRYPT_BLOCK = 117;
    //
    // /**
    //  * RSA最大解密密文大小
    //  */
    // private static final int MAX_DECRYPT_BLOCK = 128;
    //
    // /**
    //  * RSA 位数 如果采用2048 上面最大加密和最大解密则须填写:  245 256
    //  */
    // private static final int INITIALIZE_LENGTH = 1024;
    //
    // /**
    //  * 加密算法RSA
    //  */
    // public static final String KEY_ALGORITHM = "RSA";

    /**
     * 从文件中读取公钥
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String fileName) throws Exception {
        byte[] bytes = readFile(fileName);
        return getPublicKey(bytes);
    }

    /**
     * 从文件中读取私钥
     * @param fileName
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String fileName) throws Exception{
        byte[] bytes = readFile(fileName);
        return getPrivateKey(bytes);
    }

    /**
     * 获取公钥
     *
     * @param bytes
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(byte[] bytes) throws Exception {
        X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePublic(spec);
    }

    /**
     * 生成私钥
     *
     * @param bytes
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(byte[] bytes) throws Exception {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePrivate(spec);
    }

    /**
     * 读取文件
     *
     * @param fileName
     * @return
     * @throws IOException
     */
    public static byte[] readFile(String fileName) throws IOException {
        return Files.readAllBytes(new File(fileName).toPath());

    }

    // /**
    //  * 根据密文，生存rsa公钥和私钥,并写入指定文件
    //  *
    //  * @param publicKeyFilename  公钥文件路径
    //  * @param privateKeyFilename 私钥文件路径
    //  * @param secret             生成密钥的密文
    //  * @throws IOException
    //  * @throws NoSuchAlgorithmException
    //  */
    // public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret) throws Exception {
    //     KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    //     SecureRandom secureRandom = new SecureRandom(secret.getBytes());
    //     keyPairGenerator.initialize(1024, secureRandom);
    //     KeyPair keyPair = keyPairGenerator.genKeyPair();
    //     // 获取公钥并写出
    //     byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
    //     writeFile(publicKeyFilename, publicKeyBytes);
    //     // 获取私钥并写出
    //     byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
    //     writeFile(privateKeyFilename, privateKeyBytes);
    // }
    //
    // /**
    //  * 向目标路径写入文件
    //  *
    //  * @param destPath
    //  * @param bytes
    //  * @throws IOException
    //  */
    // public static void writeFile(String destPath, byte[] bytes) throws IOException {
    //     File dest = new File(destPath);
    //     if (!dest.exists()) {
    //         dest.createNewFile();
    //     }
    //     Files.write(dest.toPath(), bytes);
    // }
    //
    // /**
    //  * <P>
    //  * 私钥解密
    //  * </p>
    //  *
    //  * @param encryptedData
    //  *            已加密数据
    //  * @param privateKey
    //  *            私钥(BASE64编码)
    //  * @return
    //  * @throws Exception
    //  */
    // public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
    //     byte[] keyBytes = Base64.decodeBase64(privateKey);
    //     PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    //     KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //     Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    //     Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    //     cipher.init(Cipher.DECRYPT_MODE, privateK);
    //     int inputLen = encryptedData.length;
    //     ByteArrayOutputStream out = new ByteArrayOutputStream();
    //     int offSet = 0;
    //     byte[] cache;
    //     int i = 0;
    //     // 对数据分段解密
    //     while (inputLen - offSet > 0) {
    //         if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
    //             cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
    //         } else {
    //             cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
    //         }
    //         out.write(cache, 0, cache.length);
    //         i++;
    //         offSet = i * MAX_DECRYPT_BLOCK;
    //     }
    //     byte[] decryptedData = out.toByteArray();
    //     out.close();
    //     return decryptedData;
    // }
    //
    // /**
    //  * 公钥加密
    //  * @param data 源数据
    //  * @param publicKey 公钥(BASE64编码)
    //  * @return
    //  * @throws Exception
    //  */
    // public static String encryptByPublicKey(byte[] data, String publicKey) throws Exception {
    //     byte[] keyBytes = Base64.decodeBase64(publicKey);
    //     X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    //     KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    //     Key publicK = keyFactory.generatePublic(x509KeySpec);
    //     // 对数据加密
    //     Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    //     cipher.init(Cipher.ENCRYPT_MODE, publicK);
    //     int inputLen = data.length;
    //     // ByteArrayOutputStream out = new ByteArrayOutputStream();
    //     int offSet = 0;
    //     byte[] cache;
    //     int i = 0;
    //     // 对数据分段加密
    //     StringBuilder encode= new StringBuilder();
    //     while (inputLen - offSet > 0) {
    //         if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
    //             cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
    //         } else {
    //             cache = cipher.doFinal(data, offSet, inputLen - offSet);
    //         }
    //         encode.append(Base64.encodeBase64String(cache));
    //         // out.write(cache, 0, cache.length);
    //         i++;
    //         offSet = i * MAX_ENCRYPT_BLOCK;
    //     }
    //     // byte[] encryptedData = out.toByteArray();
    //     // out.close();
    //     return encode.toString();
    // }
    //
    // /**
    //  * java端公钥加密
    //  */
    // public static String encryptedDataOnJava(String data) {
    //     try {
    //         data = encryptByPublicKey(data.getBytes(), PUBLIC_KEY);
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //     }
    //     System.out.println(data);
    //     return data;
    // }
    //
    // /**
    //  * java端私钥解密
    //  */
    // public static String decryptDataOnJava(String data) {
    //     String temp = "";
    //     try {
    //         byte[] rs = Base64.decodeBase64(data);
    //         temp = new String(decryptByPrivateKey(rs, PRIVATE_KEY),"UTF-8");
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //     }
    //     return temp;
    // }
    //可配置到Constant中，并读取配置文件注入,16位,自己定义
    private static final String KEY = "Ha3Zie6ZufJnECBz";

    //参数分别代表 算法名称/加密模式/数据填充方式
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     * @param content 加密的字符串
     * @param encryptKey key值
     * @return
     * @throws Exception
     */
    public static String encrypt(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
        byte[] b = cipher.doFinal(content.getBytes("utf-8"));
        // 采用base64算法进行转码,避免出现中文乱码
        return Base64.encodeBase64String(b);
    }

    /**
     * 解密
     * @param encryptStr 解密的字符串
     * @param decryptKey 解密的key值
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptStr, String decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
        // 采用base64算法进行转码,避免出现中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }

    public static String encrypt(String content) throws Exception {
        return encrypt(content, KEY);
    }
    public static String decrypt(String encryptStr) throws Exception {
        return decrypt(encryptStr, KEY);
    }
}

